package org.xbzheng.restful_study.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xbzheng.restful_study.dao.UserDao;
import org.xbzheng.restful_study.model.User;
import org.xbzheng.restful_study.tool.ExceptionTool;
import org.xbzheng.restful_study.util.ResponseEntity;
import org.xbzheng.restful_study.util.ResponseError;
import org.xbzheng.restful_study.util.ResponseStatus;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Created by xiaobing.zheng on 2016/10/28.
 */
@Service
public class UserService extends BaseService{
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserDao userDao;

    public User login(final User user){
        final User dbUser = userDao.findUserByName(user.getUsername());
        if(dbUser != null && dbUser.getPassword().equals(user.getPassword())){
            return dbUser;
        }
        return null;
    }

    public User login(final String username){
        return userDao.findUserByName(username);
    }

    public String getAllUsersJson(){
        final List<User> users = userDao.findAllUser();
        final ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(users);
        } catch (final JsonProcessingException e) {
            LOGGER.error("convert to json string failed,", e);
        }
        return null;
    }

    public ResponseEntity save(final User user){
        try {
            final User result = userDao.save(user);
            return getResponseEntity(ResponseStatus.OK, new Object[]{result});
        }catch (final Exception e){
            LOGGER.error("Save user failed, The error message is : {}", e);
            return getResponseEntity(e);
        }
    }

    public ResponseEntity remove(final String ids){
        try{
            final ObjectMapper mapper = new ObjectMapper();
            final Map<String, List<Integer>> idsMap = mapper.readValue(ids, Map.class);
            if(idsMap != null && !idsMap.isEmpty()){
                final List<Integer> idsList = idsMap.get("ids");
                userDao.remove(idsList);
            }
            return getResponseEntity(ResponseStatus.OK);
        }catch (final Exception e){
            LOGGER.error("Remove user failed, The error message is : {}", e);
            return getResponseEntity(e);
        }
    }
}
